//
//  ViewController.m
//  3D_Touch
//
//  Created by Xie Wei on 2019/7/18.
//  Copyright © 2019 Xie Wei. All rights reserved.
//

#import "ViewController.h"
#import "XWTestViewController.h"

static NSString *reuseIdentifier = @"UITableViewCell";

@interface ViewController () <UIViewControllerPreviewingDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"3D Touchc测试demo";
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reuseIdentifier];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"-- 第 %ld 行 --", indexPath.row + 1];
    
    // 判断是否支持3D Touch
    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
        // 注册代理，并传入响应3D Touch的视图
        [self registerForPreviewingWithDelegate:self sourceView:cell];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - UIViewControllerPreviewingDelegate
- (nullable UIViewController *)previewingContext:(nonnull id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    NSLog(@"%@", NSStringFromCGPoint(location));
    
    UITableViewCell *cell = (UITableViewCell *)previewingContext.sourceView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    XWTestViewController *vc = [[XWTestViewController alloc] init];
    vc.index = (indexPath.row % 2 == 0 ? 0 : 1);
    
    // 调整不被虚化的范围，按压的那个cell不被虚化（轻轻按压时周边会被虚化，再少用力展示预览，再加力跳页至设定界面）
//    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width,200);
//    previewingContext.sourceRect = rect;
    return vc;
}

- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    NSLog(@"%s", __func__);
    
    [self showViewController:viewControllerToCommit sender:self];
//    [self.navigationController pushViewController:viewControllerToCommit animated:YES];
}

@end
